<?php
namespace App\Models\Traits;
use Carbon\Carbon;
use Illuminate\Support\Facades\Redis;

trait LastActiveInfoHelper{
    protected $hash_tabel_prefix='mybbs_last_active_at_';
    protected $field_prefix = 'user_';

    public function recordLastActiveAt(){
        $date = Carbon::now()->toDateString();
        //mybbs_last_active_at_2024_07_04
        $hash_table_name = $this->hash_tabel_prefix.$date;
        $hash_field_name = $this->field_prefix.$this->id;
        //dd(Redis::hGetAll($hash_table_name));
        $now_time = Carbon::now()->toDateTimeString();
        //数据以哈西表的形式写入redis 字段已存在会被更新
        Redis::hSet($hash_table_name,$hash_field_name,$now_time);
    }
    public function syncLastActivedAt(){
        //获取昨天的日期
        $yesterday_date = Carbon::yesterday()->toDateString();
        //$yesterday_date = Carbon::now()->toDateString();
        $hash_table_name = $this->hash_tabel_prefix.$yesterday_date;
        $data = Redis::hGetAll($hash_table_name);
        foreach ($data as $user_id=>$actived_at){
            $user_arr = explode('_',$user_id);
            $user_id = $user_arr[1];
            if($user = $this->find($user_id)){
                $user->last_actived_at = $actived_at;
                $user->save();
            }
        }
        Redis::del($hash_table_name);
    }

    public function getLastActivedAtAttribute($value){
        $date = Carbon::now()->toDateString();
        $hash_table_name = $this->hash_tabel_prefix.$date;
        $hash_field_name = $this->field_prefix.$this->id;

        $datetime = Redis::hGet($hash_table_name,$hash_field_name) ?: $value;
        if($datetime){
            return new Carbon($datetime);
        }else{
            //没有就以创建时间代替
            return $this->created_at;
        }
    }
}
